<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span style="font-size: 25px; font-weight: bold; ">栏目管理</span>
        <div class="extra">
          <el-button type="primary" @click="dialogVisible = true">添加栏目</el-button>
        </div>
      </div>
    </template>
    <el-table :data="columns" style="width: 100%" row-key="columnId" :row-style="tableRowStyle"
      @current-change="handleCurrentChange">
      <el-table-column label="栏目名称" prop="name"></el-table-column>
      <el-table-column label="栏目类型" prop="type"></el-table-column>
      <el-table-column label="栏目简介">
        <template v-slot="scope">
          <span v-if="scope.row.description">{{ scope.row.description }}</span>
          <span v-else>暂无简介</span>
        </template>
      </el-table-column>


      <el-table-column label="栏目展示图" width="150">
        <template #default="{ row }">
          <img v-if="row.imageUrl" :src="row.imageUrl" alt="展示图" @click="openImage(row.imageUrl)"
            style="cursor: pointer; width: 100px; height: auto;">
          <span v-else>无封面图</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button :icon="Edit" circle type="primary" @click="openEditDialog(row)"></el-button>
          <el-button :icon="Delete" circle type="danger" @click="deleteColumn(row)"></el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 图片查看器 -->
    <el-dialog v-model="dialogVisible2" title="展示图预览" width="20%" top="30vh">
      <img :src="largeImageUrl" alt="展示图" style="max-width: 100%; max-height: 80vh;">
    </el-dialog>
    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" title="栏目添加" width="30%">
      <el-form :model="columnModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <el-form-item label="父级栏目" prop="parentId">
          <el-select v-model="selectedParentId" placeholder="请选择父级栏目" @change="handleParentChange">
            <el-option v-for="column in parentColumns" :key="column.columnId" :label="`${column.name} (${column.type})`"
              :value="column.columnId">
              <template #default>
                <span>{{ column.name }}</span>
                <el-tag size="small" style="margin-left: 10px;">{{ column.type }}</el-tag>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 栏目类型选择，只在选择“无”时显示 -->
        <el-form-item label="栏目类型" prop="type" v-if="showTypeSelect">
          <el-radio-group v-model="columnModel.type">
            <el-radio label="济南市美术馆">济南市美术馆</el-radio>
            <el-radio label="济南画院">济南画院</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="columnModel.name" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="栏目简介" prop="description">
          <el-input v-model="columnModel.description" minlength="1" maxlength="15"></el-input>
        </el-form-item>

        <!-- 图片上传部分 -->
        <el-form-item label="图片" prop="imageUrl">
          <el-button type="primary" @click="handleUpload">上传图片</el-button>
          <div v-if="columnModel.imageUrl" class="image-preview">
            <img :src="columnModel.imageUrl" alt="图片预览" />
            <el-button type="danger" icon="el-icon-delete" @click="handleDeleteImage" style="width: 10px;">X</el-button>
          </div>
        </el-form-item>



        <!-- 图片尺寸 -->
        <el-form-item label="图片宽高" prop="imageSize">
          <el-input v-model="imageWidth" placeholder="宽度" style="width: 100px;"></el-input> x
          <el-input v-model="imageHeight" placeholder="高度" style="width: 100px;"></el-input>
        </el-form-item>



        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="addColumn">确认添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑分类弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑栏目" width="30%">
      <el-form :model="editColumnModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <!-- 父级栏目选择 -->
        <el-form-item label="父级栏目" prop="parentId">
          <el-select v-model="editColumnModel.parentId" placeholder="请选择父级栏目">
            <el-option v-for="column in parentColumns" :key="column.columnId" :label="column.name"
              :value="column.columnId">
              <template #default>
                <span>{{ column.name }}</span>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 栏目类型选择 -->
        <el-form-item label="栏目类型" prop="type" v-if="showTypeSelectForEdit">
          <el-radio-group v-model="editColumnModel.type">
            <el-radio label="济南市美术馆">济南市美术馆</el-radio>
            <el-radio label="济南画院">济南画院</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 栏目名称 -->
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="editColumnModel.name" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <!-- 栏目简介 -->
        <el-form-item label="栏目简介" prop="description">
          <el-input v-model="editColumnModel.description" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <!-- 图片上传部分 -->
        <el-form-item label="图片" prop="imageUrl">
          <el-button type="primary" @click="handleUploadForEdit">上传图片</el-button>
          <div v-if="editColumnModel.imageUrl" class="image-preview">
            <img :src="editColumnModel.imageUrl" alt="图片预览" />
            <el-button type="danger" icon="el-icon-delete" @click="handleDeleteImageForEdit"
              style="width: 10px;">X</el-button>
          </div>
        </el-form-item>
        <!-- 图片尺寸 -->
        <el-form-item label="图片宽高" prop="imageSize">
          <el-input v-model="editColumnModel.imageWidth" placeholder="宽度" style="width: 100px;"></el-input> x
          <el-input v-model="editColumnModel.imageHeight" placeholder="高度" style="width: 100px;"></el-input>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="updateColumn">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  </el-card>
</template>
  
<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, computed } from 'vue'
import { columnListService, getParentColumnsService, addColumnService, uploadFileService, getColumnDetailService, updateColumnService, deleteColumnService } from '@/api/column.js'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
const columns = ref([])
const currentRow = ref(null)
const parentColumns = ref([])
const selectedParentId = ref(null)
const dialogVisible = ref(false)

// 图片上传相关
const imageUrl = ref('')
const imageWidth = ref('')
const imageHeight = ref('')
const imageType = ref('')

// 添加栏目的数据模型
const columnModel = ref({
  name: '',
  parentId: null,
  description: '',
  type: '',
  imageUrl: imageUrl, // 这里应该使用 imageUrl.value，但是因为imageUrl是ref， 所以这里不能直接赋值，需要使用 ref.value
  imageWidth: imageWidth, // 同上
  imageHeight: imageHeight, // 同上
  imageType: imageType // 同上
})

// 添加分类表单校验
const rules = {
  name: [
    { required: true, message: '请输入栏目名称', trigger: 'blur' },
  ]
}
// 控制栏目类型显示的响应式数据
const showTypeSelect = ref(false);

// 父级栏目改变时的处理函数
const handleParentChange = (parentId) => {
  // 只有在选择“无”时，才显示栏目类型选择
  showTypeSelect.value = parentId === null;
  // 清空栏目类型，以防之前有选择
  columnModel.value.type = '';
};

// 添加栏目的方法
const addColumn = async () => {
  // 确保 imageUrl 是响应式的值
  columnModel.value.imageUrl = imageUrl.value;
  columnModel.value.parentId = selectedParentId.value === '无' ? null : selectedParentId.value;
  columnModel.value.imageWidth = imageWidth.value;
  columnModel.value.imageHeight = imageHeight.value;
  columnModel.value.imageType = imageType.value;
  // 如果栏目类型选择被显示了，确保它的值被发送到服务器
  if (showTypeSelect.value) {
    columnModel.value.type = columnModel.value.type;
  }
  console.log(columnModel.value);
  const response = await addColumnService(columnModel.value);
  if (response.code == 200) {
    ElMessage.success('添加成功')
    // 重置表单数据

    resetColumnModel();
    fetchColumns();
  } else {
    ElMessage.error('添加失败')
  }
  // 关闭弹窗（这里应该使用 dialogVisible.value = false;
  dialogVisible.value = false;
  // 其他逻辑，比如刷新列表
}


// 图片上传相关
const handleUpload = async () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.click();

  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      const response = await uploadFileService(file); // 使用 uploadFile 方法
      if (response.code === 200) {
        ElMessage.success('图片上传成功');
        imageUrl.value = response.data; // 设置图片URL
        // 可以在这里设置图片的宽高和类型，如果服务器返回了这些信息
      } else {
        // 处理上传失败的情况
        ElMessage.error('图片上传失败');
      }
    } catch (error) {
      console.error('上传失败', error);
      ElMessage.error('图片上传失败');
    }
  };
};

// 定义响应式数据
const dialogVisible2 = ref(false);
const largeImageUrl = ref('');
const largeTitle = ref('');
const laegeDescription = ref('');
// 预览图片方法定义
const openImage = (url) => {
  largeImageUrl.value = url;
  dialogVisible2.value = true;
};


const handleDeleteImage = () => {
  imageUrl.value = '';
  imageWidth.value = '';
  imageHeight.value = '';
  imageType.value = '';
};

const fetchColumns = async () => {
  let result = await columnListService()
  columns.value = formatColumns(result.data)
}

const formatColumns = (data) => {
  const map = {}
  const result = []
  data.forEach(item => {
    map[item.columnId] = { ...item, children: [] }
  })
  data.forEach(item => {
    if (item.parentId) {
      map[item.parentId].children.push(map[item.columnId])
    } else {
      result.push(map[item.columnId])
    }
  })
  return result
}

const tableRowStyle = ({ row }) => {
  const isChild = !!row.parentId; // 子栏目通常会有 parentId

  if (isChild) {
    return { backgroundColor: '#fcfffa' }; // 子栏目的底色
  } else {
    // 父栏目根据奇偶行改变颜色
    const rowIndex = row.rowIndex !== undefined ? row.rowIndex : 0;
    return rowIndex % 2 === 0 ? { backgroundColor: 'rgba(248, 247, 247, 0.667)' } : { backgroundColor: '#f9f9f9' };
  }
};

const processColumns = (data) => {
  let parentIndex = -1; // 用于追踪父栏目索引

  return data.map((item, index) => {
    if (!item.parentId) { // 如果是父栏目
      parentIndex += 1;
    }

    return {
      ...item,
      rowIndex: item.parentId ? undefined : parentIndex, // 只给父栏目设置rowIndex
    };
  });
}

const handleCurrentChange = (val) => {
  currentRow.value = val
}

const fetchParentColumns = async () => {
  const result = await getParentColumnsService();
  parentColumns.value = result.data;
  parentColumns.value.unshift({ columnId: null, name: '无' });
}

// 编辑弹窗相关
const editDialogVisible = ref(false);
const editColumnModel = ref({
  columnId: null,
  parentId: null,
  name: '',
  type: '',
  description: '',
  imageUrl: '',
  imageWidth: '',
  imageHeight: ''
});
const showTypeSelectForEdit = ref(false); // 控制编辑弹窗中栏目类型选择显示

// 获取栏目详情
const getColumnDetail = async (columnId) => {
  const response = await getColumnDetailService(columnId);
  if (response.code === 200) {
    editColumnModel.value = { ...response.data };
    // 根据父栏目选择控制栏目类型选择是否显示
    showTypeSelectForEdit.value = editColumnModel.value.parentId === null;
  }
};

// 更新栏目
const updateColumn = async () => {
  const response = await updateColumnService(editColumnModel.value);
  if (response.code === 200) {
    ElMessage.success('更新成功');
    // 关闭弹窗，刷新列表等操作
    editDialogVisible.value = false;
    fetchColumns();
  } else {
    ElMessage.error('更新失败');
  }
};

// 在 openEditDialog 方法中调用 getColumnDetail
const openEditDialog = async (row) => {
  await getColumnDetail(row.columnId);
  editDialogVisible.value = true;
};

// 图片上传相关
const handleUploadForEdit = async () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.click();

  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      const response = await uploadFileService(file); // 使用 uploadFile 方法
      if (response.code === 200) {
        ElMessage.success('图片上传成功');
        editColumnModel.value.imageUrl = response.data; // 设置图片URL
        // 如果服务器返回了图片的宽高和类型，可以在这里设置
        // editColumnModel.value.imageWidth = response.data.width;
        // editColumnModel.value.imageHeight = response.data.height;
        // editColumnModel.value.imageType = response.data.type;
      } else {
        // 处理上传失败的情况
        ElMessage.error('图片上传失败');
      }
    } catch (error) {
      console.error('上传失败', error);
      ElMessage.error('图片上传失败');
    }
  };
};

const handleDeleteImageForEdit = () => {
  editColumnModel.value.imageUrl = '';
  editColumnModel.value.imageWidth = '';
  editColumnModel.value.imageHeight = '';
  // 如果有图片类型字段，也应该清空
  // editColumnModel.value.imageType = '';
};


// 删除栏目的方法
const deleteColumn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个栏目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const response = await deleteColumnService(row.columnId);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      // 删除成功后，重新获取栏目列表
      fetchColumns();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    // 用户点击取消按钮或操作被取消
    if (error !== 'cancel') {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }
};

// 重置栏目模型的方法
const resetColumnModel = () => {
  columnModel.value = {
    name: '',
    parentId: null,
    description: '',
    type: '',
    imageUrl: '',
    imageWidth: '',
    imageHeight: '',
    imageType: ''
  };
  imageUrl.value = '';
  imageWidth.value = '';
  imageHeight.value = '';
  imageType.value = '';
  showTypeSelect.value = false; // 确保栏目类型选择框在重置后不显示
  selectedParentId.value = null; // 重置父级栏目的选择
}


onMounted(() => {
  fetchColumns();
  fetchParentColumns();
  columns.value = processColumns(columns.value); // 处理数据
})
</script>
  
  
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {

    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  /* 表格表头样式 */
  :deep(.el-table__header th) {
    background-color: #eeefed;
    font-size: 16px;
    color: #717171;
    font-weight: bold;
    // padding: 15px;

  }


  .image-preview {
    margin-top: 10px;
    position: relative;
  }

  .image-preview img {
    max-width: 100%;
    height: auto;
  }

  .image-preview .el-button {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
</style>
  